package cn.xiaohaoo.admin.controller;

import ai.onnxruntime.OrtException;
import cn.xiaohaoo.admin.entity.ResponseResult;
import cn.xiaohaoo.admin.service.MedicinePredictionService;
import cn.xiaohaoo.admin.service.MedicineService;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("medicine")
@Slf4j
public class MedicineController {
    @Autowired
    private MedicineService medicineService;

    @GetMapping("outlines")
    public ResponseResult<List<Document>> getAllMedicineOutlines(@RequestParam(required = false) String name) {
        if (StringUtils.hasText(name)) {
            return ResponseResult.success(medicineService.getAllMedicineOutlines(name));
        } else {
            return ResponseResult.success(medicineService.getAllMedicineOutlines());
        }
    }

    @GetMapping(value = "details", params = {"name"})
    public ResponseResult<Document> getDetailsByName(@RequestParam String name) {
        return ResponseResult.success(medicineService.queryMedicineDetail(name));
    }


    @GetMapping(value = "details",params = {"keyword"})
    public ResponseResult<List<Document>> getDetails(@RequestParam String keyword) throws IOException {
        return ResponseResult.success(medicineService.queryMedicineDetails(keyword));
    }


    @Autowired
    private MedicinePredictionService medicineModelService;

    @PostMapping(value = "prediction")
    public ResponseResult<Map<String, Float>> predictionByPicture(MultipartFile picture) throws IOException,
        OrtException {
        try (InputStream inputStream = picture.getInputStream()) {
            return ResponseResult.success(medicineModelService.prediction(inputStream));
        }
    }
}
